var ws = null;

//专门用来写长连接
function loginSuccess(){
    var userId = localStorage.getItem("userId");
    //如果为空就不连
    if(userId == null){
        return;
    }
    //WebSocket对象
    ws = new WebSocket("ws://192.168.1.16:80/private/chat/"+userId);

    //连接成功时
    ws.onopen = function(){
        console.log("连接成功");
    }
    //连接关闭时
    ws.onclose = function(){
        console.log("连接关闭");
        setTimeout(()=>{
            loginSuccess();
        },2000);
    }
    //收到服务器的信息
    ws.onmessage = function(e){
        console.log("收到后端信息",e);
        //把收到的信息放到message-box里面
        var data = JSON.parse(e.data);
        $("#message-box").append("<p>"+data.nickName+"说："+data.msg+"</p>");
        //滚动条到底部
        $("#message-box").scrollTop($("#message-box")[0].scrollHeight);
    }
    //连接异常
    ws.onerror = function(e){
        console.log(e);
    }
}
//去触发长连接
loginSuccess();

